import { DataTypes } from 'sequelize';
import bcrypt from 'bcryptjs';
import { sequelize } from '../config/database.js';

const User = sequelize.define('User', {
  id: {
    type: DataTypes.INTEGER,
    primaryKey: true,
    autoIncrement: true
  },
  phone: {
    type: DataTypes.STRING(20),
    allowNull: false,
    comment: '手机号'
  },
  email: {
    type: DataTypes.STRING(255),
    allowNull: true,
    validate: {
      isEmail: true
    },
    comment: '邮箱'
  },
  name: {
    type: DataTypes.STRING(100),
    allowNull: true,
    comment: '真实姓名'
  },
  nickname: {
    type: DataTypes.STRING(100),
    allowNull: true,
    comment: '昵称'
  },
  avatar: {
    type: DataTypes.STRING(500),
    allowNull: true,
    comment: '头像URL'
  },
  password: {
    type: DataTypes.STRING(255),
    allowNull: true,
    comment: '密码哈希'
  },
  register_channel: {
    type: DataTypes.STRING(50),
    allowNull: true,
    comment: '注册渠道'
  },
  last_login_at: {
    type: DataTypes.DATE,
    allowNull: true,
    comment: '最后登录时间'
  },
  last_login_ip: {
    type: DataTypes.STRING(45),
    allowNull: true,
    comment: '最后登录IP'
  },
  is_active: {
    type: DataTypes.BOOLEAN,
    defaultValue: true,
    comment: '是否激活'
  },
  created_at: {
    type: DataTypes.DATE,
    defaultValue: DataTypes.NOW
  },
  updated_at: {
    type: DataTypes.DATE,
    defaultValue: DataTypes.NOW
  }
}, {
  tableName: 'users',
  timestamps: true,
  createdAt: 'created_at',
  updatedAt: 'updated_at',
  indexes: [
    {
      name: 'idx_users_phone',
      unique: true,
      fields: ['phone'],
    },
    {
      name: 'idx_users_email_unique',
      unique: true,
      fields: ['email'],
      where: {
        email: {
          [sequelize.Sequelize.Op.ne]: null,
          [sequelize.Sequelize.Op.ne]: ''
        }
      }
    },
    {
      name: 'idx_users_nickname_unique',
      unique: true,
      fields: ['nickname'],
      where: {
        nickname: {
          [sequelize.Sequelize.Op.ne]: null,
          [sequelize.Sequelize.Op.ne]: ''
        }
      }
    },
    {
      name: 'idx_users_is_active',
      fields: ['is_active'],
    },
  ],
  hooks: {
    beforeCreate: async (user) => {
      if (user.password) {
        user.password = await bcrypt.hash(user.password, 12);
      }
    },
    beforeUpdate: async (user) => {
      if (user.changed('password') && user.password) {
        user.password = await bcrypt.hash(user.password, 12);
      }
    }
  }
});

// 实例方法
User.prototype.toJSON = function() {
  const values = { ...this.get() };
  delete values.password; // 不返回密码
  return values;
};

User.prototype.validatePassword = async function(password) {
  if (!this.password) return false;
  return await bcrypt.compare(password, this.password);
};

User.prototype.updateLoginInfo = async function(ip) {
  this.last_login_at = new Date();
  this.last_login_ip = ip;
  await this.save();
};

// 类方法
User.findByPhone = function(phone) {
  return this.findOne({ where: { phone } });
};

User.findByEmail = function(email) {
  return this.findOne({ where: { email } });
};

User.findByNickname = function(nickname) {
  return this.findOne({ where: { nickname } });
};

User.createUser = async function(userData) {
  return await this.create(userData);
};

User.findWithQuotas = function(id) {
  return this.findByPk(id, {
    include: [{
      association: 'quotas',
      where: { remaining_count: { [sequelize.Sequelize.Op.gt]: 0 } },
      required: false,
      include: [
        { association: 'domain', attributes: ['id', 'name'] },
        { association: 'expert', attributes: ['id', 'nickname'] }
      ]
    }]
  });
};

export default User;
